package com.stress.testing.agent;

import com.stress.testing.agent.resolver.AgentResourceResolver;
import com.stress.testing.common.AgentContext;
import com.stress.testing.common.ClassFileTransformerRegistry;
import com.stress.testing.common.DefaultAgentContext;
import com.stress.testing.common.conf.AgentConfig;
import com.stress.testing.common.conf.AgentConfigLoader;
import com.stress.testing.common.conf.DefaultAgentConfigLoader;
import com.stress.testing.instrumentation.ByteBuddyClassFileTransformerRegistry;

import java.lang.instrument.Instrumentation;

public class AgentStarter {
    private Instrumentation inst;
    private AgentResourceResolver agentResourceResolver;

    public AgentStarter(Instrumentation inst, AgentResourceResolver agentResourceResolver) {
        this.inst = inst;
        this.agentResourceResolver = agentResourceResolver;
    }

    public void start() {
        // 解析agent配置
        AgentConfigLoader agentConfigLoader = new DefaultAgentConfigLoader();
        AgentConfig agentConfig = agentConfigLoader.load(agentResourceResolver.getAgentConfigFullName());

        // 构造第三方jar类加载器
        // ** 没有解决bytebuddy的问题，jar都打进agent里，这里不需要了
        /*List<URL> urlList = new ArrayList<>();
        urlList.addAll(agentResourceResolver.getExtendLibURL());
        urlList.addAll(agentResourceResolver.getAgentDependenceURL());
        URL[] urls = urlList.toArray(new URL[urlList.size()]);

        AgentJarClassMatcher agentJarClassMatcher = new NameSpacePrefixClassMatcher(
                agentConfig.getClassFileTransformerRegistryClass());

        AgentExtendJarClassLoader agentExtendJarClassLoader = new AgentExtendJarClassLoader(urls,
                AgentStarter.class.getClassLoader(), agentJarClassMatcher);*/

        // 构造agent上下文
        AgentContext agentContext = new DefaultAgentContext(agentConfig,
                agentResourceResolver.getExtendLibURL(),
                agentResourceResolver.getAgentDependenceURL(),
                agentResourceResolver.getAgentPluginURL(),
                inst,
                AgentStarter.class.getClassLoader(),
                agentResourceResolver.getAgentPluginPath());

        // 向inst中添加ClassFileTransformer
        // ** 没有解决bytebuddy的问题，jar都打进agent里，这里不需要了
        /*ClassFileTransformerRegistryResolver classFileTransformerRegistryResolver =
                new DefaultClassFileTransformerRegistryResolver();
        ClassFileTransformerRegistry classFileTransformerRegistry =
                classFileTransformerRegistryResolver.resolve(agentContext);
        classFileTransformerRegistry.register(agentContext);*/

        ClassFileTransformerRegistry classFileTransformerRegistry = new ByteBuddyClassFileTransformerRegistry();


        classFileTransformerRegistry.register(agentContext);
    }
}
